<?php


namespace App\Controller\User;


use App\Base\BaseController4Restful;
use App\Entity\User;
use App\Event\UserEvent;
use App\Repository\Trade\UserTradeRepository;
use App\Repository\UserRepository;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Routing\Annotation\Route;

class TradeUserController extends BaseController4Restful
{

    /**
     * @Route("/app/trade/user/login", name="ApiTradeUserLogin")
     */
    public function ApiTradeUserLogin(
        UserRepository $userRepository,
        EventDispatcherInterface $dispatcher
    )
    {
        $req = $this->getRequestData();
        $phone = $req['phone']??'';
        $user = $userRepository->getByPhone($phone);
        if (!$user) {
            $user = new User();
            $user->setPhone($phone)
                ->setCreateAt(new \DateTime())
                ->setName($phone)
                ->setApiToken($phone)
                ->setIsOn(true);
            $this->myEm()->persist($user);
            $this->myEm()->flush();

            //触发用户注册事件
            $event = new UserEvent($user);
            $dispatcher->dispatch($event,UserEvent::USER_REG);
        }
        return $this->json_out(1,"OK",$user);
    }
    /**
     * @Route("/app/trade/user/info", name="ApiTradeUserInfo")
     */
    public function ApiTradeUserInfo(
        UserTradeRepository $repository,EventDispatcherInterface $dispatcher
    )
    {
        $user = $this->needToBeUser();

        $tUser = $repository->findOneBy(array("user"=>$user));
        if (!$tUser) {
            //触发用户注册事件
            $event = new UserEvent($user);
            $dispatcher->dispatch($event,UserEvent::USER_REG);
            $tUser = $repository->findOneBy(array("user"=>$user));
        }
        $this->setGroups("user");
        return $this->json_out(1,"OK",$tUser);
    }
}
